package com.scu.dao;

import com.scu.entity.User;
import com.scu.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    //添加一个用户
    public int insert(User user) throws SQLException {
        //1. 连接
        Connection conn = JDBCUtil.getConnection();

        //2. sql
        String sql = "INSERT INTO USER(user_id,password,name,phone,email) VALUES(?,?,?,?,?)";
        PreparedStatement prep = conn.prepareStatement(sql);
        prep.setInt(1,user.getUser_id());
        prep.setString(2,user.getPassword());
        prep.setString(3,user.getName());
        prep.setString(4,user.getPhone());
        prep.setString(5,user.getEmail());

        //3. 结果
        int row = prep.executeUpdate();

        //4. 关闭连接
        conn.close();

        return row;
    }

    //删除
    public int delete(int user_id) throws SQLException {
        //1. 连接
        Connection conn = JDBCUtil.getConnection();

        //2. sql
        String sql = "delete from user where user_id=?";
        PreparedStatement prep = conn.prepareStatement(sql);
        prep.setInt(1,user_id);

        //3. 结果
        int row = prep.executeUpdate();

        //4. 关闭连接
        conn.close();

        return row;
    }

    public List<User> findAllUser() throws SQLException {
        //1. 连接
        Connection conn = JDBCUtil.getConnection();

        //2. sql
        String sql = "select * from user";
        PreparedStatement prep = conn.prepareStatement(sql);

        //3. 结果
        ResultSet rs = prep.executeQuery();
        //处理结果
        List<User> list = new ArrayList<User>();
        while(rs.next()){
            //rs代表的就是每一行
            User user = new User();

            int user_id = rs.getInt("user_id");
            String password = rs.getString("password");
            String name = rs.getString("name");
            String phone = rs.getString("phone");
            String email = rs.getString("email");


            user.setUser_id(user_id);
            user.setPassword(password);
            user.setName(name);
            user.setPhone(phone);
            user.setEmail(email);

            list.add(user);
        }

        //4. 关闭连接
        conn.close();

        return list;
    }

    public static void main(String[] args) throws SQLException {
        List<User> list = new UserDao().findAllUser();
        System.out.println(list);
    }
}